import 'dart:math';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:orginone/components/FloatButton/FloatButton.dart';
import 'package:orginone/components/TabContainerWidget/types.dart';
import 'package:orginone/components/EmptyWidget/EmptyActivity.dart';
import 'package:orginone/components/XButton/XButton.dart';
import 'package:orginone/config/theme/unified_style.dart';
import 'package:orginone/dart/core/chat/activity.dart';
import 'package:orginone/dart/extension/ex_widget.dart';
import 'package:orginone/routers/pages.dart';
import 'package:orginone/utils/log/log_util.dart';
import '../../../main.dart';
import '../../../routers/app_route.dart';
import '../../CommandWidget/index.dart';
import '../../XButtonBar/XButtonBar.dart';
import '../../XImage/XImage.dart';
import '../../XLazy/XLazy.dart';
import 'components/ActivityMessageWidget/ActivityMessageWidget.dart';

//渲染动态列表
class ActivityListWidget extends StatefulWidget {
  late final ScrollController _scrollController;
  late final IActivity? _activity;
  late final int? showCount;
  late final bool? isFromChat;

  ActivityListWidget(
      {super.key,
      this.showCount,
      this.isFromChat,
      scrollController,
      activity}) {
    var parentParam = RoutePages.getParentRouteParam();
    _scrollController = scrollController ?? ScrollController();
    _activity = activity ?? (parentParam is IActivity ? parentParam : null);
  }
  @override
  State<StatefulWidget> createState() => _ActivityListState();
}

class _ActivityListState extends State<ActivityListWidget> {
  ScrollController get _scrollController => widget._scrollController;
  IActivity? get _activity => widget._activity;
  int? get showCount => widget.showCount;
  bool? get isFromChat => widget.isFromChat ?? false;
  late final String? _key;

  @override
  void initState() {
    super.initState();
    //订阅数据变更
    _key = _activity?.subscribe((key, args) {
      if (mounted) {
        setState(() {});
      }
    }, false);
  }

  @override
  void dispose() {
    super.dispose();
    _activity?.unsubscribe(_key);
  }

  @override
  void didUpdateWidget(covariant ActivityListWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {
    return null != _activity
        ? null != showCount
            ? _buildActivity(activity: _activity!)
            : _buildActivityContainer(
                activity: _activity!, isFromChat: isFromChat ?? false)
        : const EmptyActivity();
  }

  Widget _buildActivity({required IActivity activity}) {
    int i = 0;
    List<IActivityMessage> activityMessages =
        activity.activityList.sublist(0, min(2, activity.activityList.length));
    return Column(
      children: activityMessages.map((item) {
        return Container(
            decoration: const BoxDecoration(
              color: XColors.bgListItem,
              border: Border(
                bottom: BorderSide(
                  width: 1,
                  color: XColors.dividerLineColor,
                ),
              ),
            ),
            child: ActivityMessageWidget(
              currIndex: i++,
              item: item,
              activity: activity,
              hideResource: true,
            ));
      }).toList(),
    );
  }

  loadLatestData() async {
    await _activity!.load(reload: true);
    setState(() {});
  }

  loadDataMore() async {
    await _activity!.load();
    setState(() {});
    XLogUtil.d("load more : size=${_activity!.activityList.length}");
  }

  Widget _buildActivityList(IActivity activity) {
    return Container(
      color: XColors.white,
      child: XLazy<IActivityMessage>(
        initDatas: activity.activityList ?? [],
        onInitLoad:  () async {
          return activity.activityList;
        },
        onLoad: () async {
          loadDataMore();
          return activity.activityList;
        },
        scrollController: _scrollController,
        builder: (context, datas) {
          return (activity.activityList.isEmpty)
              ? const EmptyActivity()
              : ListView(
              controller: _scrollController,
              children: _buildActivityItem(activity: _activity!));
        },
      ),
    );
  }

  Widget addBottomBtnWidget({required Widget child, Function()? onPressed}) {
    return XButtonBar(
      body: child,
      listAction: [
        ActionModel(
            title: "发表动态",
            onTap: () {
              if (onPressed != null) {
                onPressed();
              }
            })
      ],
    );
  }

  Widget _actionWidget(
      {required String buttonTooltip,
      Function()? onPressed,
      required Widget child}) {
    return Stack(
      children: [
        child,
        Positioned(
          right: 10,
          bottom: 20,
          child: XButton.iconCustomText(
            onPressed: onPressed,
            icon: XImage.localImage(XImage.add, width: 13, color: Colors.white),
            text: '  发布',
            iconLeft: true,
            bgcolor: const Color(0xFF0052D9),
            textColor: Colors.white,
          ),
        ),
      ],
    );
    // return FloatButton(
    //   onPressed: onPressed,
    //   tooltip: buttonTooltip,
    //   icon: const Icon(Icons.add),
    //   child: child,
    // );
  }

  //渲染动态列表
  List<Widget> _buildActivityItem({required IActivity activity}) {
    List<Widget> list = [];
    for (int i = 0; i < activity.activityList.length; i++) {
      list.add(Container(
        decoration: const BoxDecoration(
          color: XColors.bgListItem,
          border: Border(
            bottom: BorderSide(
              width: 1,
              color: XColors.dividerLineColor,
            ),
          ),
        ),
        child: ActivityMessageWidget(
          currIndex: i,
          activity: activity,
          hideResource: true,
        ),
      ));
    }
    return list;
  }

  Widget _buildActivityContainer(
      {required IActivity activity, bool isFromChat = false}) {
    Widget content = _buildActivityList(activity);
    if (activity.activityList.isEmpty) {
      content = FutureBuilder<List<IActivityMessage>>(
          builder: (context, shot) {
            if (shot.hasData && shot.connectionState == ConnectionState.done) {
              return _buildActivityList(activity);
            }
            return const Center(
              child: CircularProgressIndicator(),
            );
          },
          future: activity.load());
    }
    if (activity.allPublish) {
      if (isFromChat) {
        content = addBottomBtnWidget(
          // buttonTooltip: "发表动态",
          onPressed: () {
            RoutePages.jumpActivityRelease(context, activity: activity);
          },
          child: content,
        );
      } else {
        content = _actionWidget(
          buttonTooltip: "发表动态",
          onPressed: () {
            RoutePages.jumpActivityRelease(context, activity: activity);
          },
          child: content,
        );
      }
    }
    return content;
  }
}
